package com.ruoyi.hd.service.impl;

import java.util.Date;
import java.util.List;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.hd.mapper.SqlUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.hd.domain.HdCommodityTime;
import com.ruoyi.hd.mapper.HdCommodityMapper;
import com.ruoyi.hd.domain.HdCommodity;
import com.ruoyi.hd.service.IHdCommodityService;

import javax.validation.Validator;

/**
 * 商品管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-05-29
 */
@Service
public class HdCommodityServiceImpl implements IHdCommodityService 
{
    private static final Logger log = LoggerFactory.getLogger(HdCommodityServiceImpl.class);
    @Autowired
    private HdCommodityMapper hdCommodityMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ISysConfigService configService;


    /**
     * 查询商品管理
     * 
     * @param id 商品管理主键
     * @return 商品管理
     */
    @Override
    public HdCommodity selectHdCommodityById(Long id)
    {
        return hdCommodityMapper.selectHdCommodityById(id);
    }

    /**
     * 查询商品管理列表
     * 
     * @param hdCommodity 商品管理
     * @return 商品管理
     */
    @Override
    public List<HdCommodity> selectHdCommodityList(HdCommodity hdCommodity)
    {
        return hdCommodityMapper.selectHdCommodityList(hdCommodity);
    }

    /**
     * 新增商品管理
     * 
     * @param hdCommodity 商品管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertHdCommodity(HdCommodity hdCommodity)
    {
        hdCommodity.setCreateTime(DateUtils.getNowDate());
        hdCommodity.setBatch(DateUtils.parseDateToStr("yyMMddHHmm", new Date()));
        int rows = hdCommodityMapper.insertHdCommodity(hdCommodity);
        insertHdCommodityTime(hdCommodity);
        return rows;
    }

    /**
     * 修改商品管理
     * 
     * @param hdCommodity 商品管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateHdCommodity(HdCommodity hdCommodity)
    {
        hdCommodity.setUpdateTime(DateUtils.getNowDate());
        hdCommodityMapper.deleteHdCommodityTimeByCommodityId(hdCommodity.getId());
        insertHdCommodityTime(hdCommodity);
        return hdCommodityMapper.updateHdCommodity(hdCommodity);
    }

    /**
     * 批量删除商品管理
     * 
     * @param ids 需要删除的商品管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHdCommodityByIds(Long[] ids)
    {
        hdCommodityMapper.deleteHdCommodityTimeByCommodityIds(ids);
        return hdCommodityMapper.deleteHdCommodityByIds(ids);
    }

    /**
     * 删除商品管理信息
     * 
     * @param id 商品管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHdCommodityById(Long id)
    {
        hdCommodityMapper.deleteHdCommodityTimeByCommodityId(id);
        return hdCommodityMapper.deleteHdCommodityById(id);
    }

    /**
     * 导入商品数据
     *
     * @param commodityList 商品数据列表
     * @param isUpdateSupport          是否更新支持，如果已存在，则进行更新数据
     * @param operName                 操作用户
     * @return 结果
     */
    @Override
    public String importHdCommodity(List<HdCommodity> commodityList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(commodityList) || commodityList.size() == 0) {
            throw new ServiceException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (HdCommodity commodity : commodityList) {
            try {
                // 验证是否存在这个名称
                HdCommodity er = hdCommodityMapper.selectHdCommodityByName(commodity.getName());
                if (StringUtils.isNull(er)) {
                    BeanValidators.validateWithException(validator, commodity);
                    commodity.setCreateBy(operName);
                    this.insertHdCommodity(commodity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品名称 " + commodity.getName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, commodity);
                    commodity.setId(er.getId());
                    commodity.setUpdateBy(operName);
                    this.updateHdCommodity(commodity);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品名称 " + commodity.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、商品名称 " + commodity.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品名称" + commodity.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 新增商品记录管理信息
     * 
     * @param hdCommodity 商品管理对象
     */
    public void insertHdCommodityTime(HdCommodity hdCommodity)
    {
        List<HdCommodityTime> hdCommodityTimeList = hdCommodity.getHdCommodityTimeList();
        Long id = hdCommodity.getId();
        if (StringUtils.isNotNull(hdCommodityTimeList))
        {
            List<HdCommodityTime> list = new ArrayList<HdCommodityTime>();
            for (HdCommodityTime hdCommodityTime : hdCommodityTimeList)
            {
                hdCommodityTime.setCommodityId(String.valueOf(id));
                list.add(hdCommodityTime);
            }
            if (list.size() > 0)
            {
                hdCommodityMapper.batchHdCommodityTime(list);
            }
        }
    }
}
